var ctx=window.daijia.ctx;
var lng=window.daijia.lng;
var lat=window.daijia.lat;
var allmap2=null;//跑腿地图对象
var map2=null;
var isfirst2=true;//地图第一次加载
var distance=null;
var timeStr=null;
var driving=null;
var start = new Array();
var end = new Array();
var areaId=null;//类型对应的收费id
var endAdd=null;//目的地是否选填
var addressPoint = new Array();
var areaWeightId = null;//重量收费id
function initialize2(){
	var point=new BMap.Point(lng,lat);
	
	if (point) {
		map2 = new BMap.Map("allmap2");  
		map2.centerAndZoom(point, 13);
		map2.enableScrollWheelZoom();
		 driving = new BMap.DrivingRoute(map2, {    
			policy : BMAP_DRIVING_POLICY_LEAST_DISTANCE,
			onSearchComplete: function(results){   
				if (driving.getStatus() == BMAP_STATUS_SUCCESS){  
				 // 获取第一条方案   
				 var plan = results.getPlan(0); 
				  distance=plan.getDistance();
				  timeStr=plan.getDuration(); 
				 $.post(ctx+"/errand/up/getPrice",
						   {areaId:areaId,
					 		areaWeightId:areaWeightId,
					 		weight:$("#weight").val(),
					 		thanksCash:$("#thanksCash").val(),
					 		goodsCash:$("#goodsCash").val(),
					 		couponId:$("#errand_couponId").val(),
					 		protectPrice:$("#protectPrice").val(),
						    time:timeStr,
						    mileage:distance},function(data){							    								    	
						    	$("#shouldPay").val(data.money);
						    	$("#startPrice").val(data.startPrice);
						    	$("#mileagePrice").val(data.mileagePrice);
						    	$("#travelTimePrice").val(data.travelTimePrice);
						    	$("#travelTime").val(data.travelTime);
						    	$("#mileage").val(data.mileage);
						    	$("#weightPrice").val(data.weightPrice);
						    	$(".errand_travelTime").text("预计时间:"+data.travelTime+"分钟");
						       	$(".errand_mileage").text("预计路程:"+data.mileage+"公里");
						    },"json");
			    }    
			},
			renderOptions: {    //显示到地图上
							map: map2,    
							autoViewport: true 
			}     
		});
	    //右键菜单
	    var contextMenu = new BMap.ContextMenu();
		var txtMenuItem = [{
			  text:'设为任务任务起点',
			   callback:function(p){
				   map2.clearOverlays();
			   		
			   		var memberMarker = new BMap.Marker(p);  // 创建标注
			   		map2.addOverlay(memberMarker);
	    			
	    			var gc = new BMap.Geocoder();
				    gc.getLocation(p, function(rs){
				        var addComp = rs.addressComponents;
				        $("#startAddress").val(addComp.street);
				        $("#startAddress").attr("lng",p.lng);
				        $("#startAddress").attr("lat",p.lat);
				        $.post(ctx+"/errand/up/getPrice",
								   {areaId:areaId,
				        			areaWeightId:areaWeightId,
				        			couponId:$("#errand_couponId").val(),
				        			weight:$("#weight").val(),
						 			thanksCash:$("#thanksCash").val(),
						 			goodsCash:$("#goodsCash").val(),
						 			protectPrice:$("#protectPrice").val(),
								    time:timeStr,
								    mileage:distance},function(data){							    								    	
								    	$("#shouldPay").val(data.money);
								    	$("#startPrice").val(data.startPrice);
								    	$("#mileagePrice").val(data.mileagePrice);
								    	$("#travelTimePrice").val(data.travelTimePrice);
								    	$("#travelTime").val(data.travelTime);
								    	$("#mileage").val(data.mileage);
								    	$("#weightPrice").val(data.weightPrice);
								    	$(".errand_travelTime").text("预计时间:"+data.travelTime+"分钟");
								       	$(".errand_mileage").text("预计路程:"+data.mileage+"公里");
								    },"json");
				        start[0]=p.lng;
				        start[1]=p.lat; 
				        if(end.length!=0){
				        	var startPoint=new BMap.Point(start[0], start[1]);
							var endPoint=new BMap.Point(end[0],end[1]);
							map2.centerAndZoom(startPoint, 10); 
							driving.search(startPoint, endPoint);
				        }
				        if(addComp.street+addComp.streetNumber != ""){
				        	$("#startAddress").val(addComp.street+" "+addComp.streetNumber);
				        }else{
				        	$("#startAddress").val("");
				        	$.scojs_message("起点地址获取失败，请填写起点,手动定位", $.scojs_message.TYPE_ERROR);
				        }
				        if(rs.surroundingPois[0].title.trim()!=null && rs.surroundingPois[0].title.trim()!=""){
				        	$("#detailedAddress").val(rs.surroundingPois[0].title);
				        }
				    });         
			   }},{
		   text:'设为任务任务终点',
		   callback:function(p){
			   map2.clearOverlays();
		   		
		   		var memberMarker = new BMap.Marker(p);  // 创建标注
		   		map2.addOverlay(memberMarker);
    			
    			var gc = new BMap.Geocoder();
			    gc.getLocation(p, function(rs){
			        var addComp = rs.addressComponents;
			        if(addComp.street+addComp.streetNumber != ""){
			        	$("#deliverAddress").val(addComp.street+" "+addComp.streetNumber);
			        }else{
			        	$("#deliverAddress").val("");
			        	$.scojs_message("终点地址获取失败，请填写终点，手动定位", $.scojs_message.TYPE_ERROR);
			        }
			        $("#deliverAddress").attr("lng",p.lng);
			        $("#deliverAddress").attr("lat",p.lat);
			        end[0]=p.lng;
			        end[1]=p.lat;
			        if(start.length!=0){
				        var startPoint=new BMap.Point(start[0], start[1]);
						var endPoint=new BMap.Point(p.lng,p.lat);
						map2.centerAndZoom(startPoint, 10); 
						driving.search(startPoint, endPoint);
					}
			        $("#deliverDetailedAddress").val("");
			        if(rs.surroundingPois[0].title.trim()!=null && rs.surroundingPois[0].title.trim()!=""){
			        	$("#deliverDetailedAddress").val(rs.surroundingPois[0].title);
			        }
			    });         
		   }
		}];
		
		
		for(var i=0; i < txtMenuItem.length; i++){
			contextMenu.addItem(new BMap.MenuItem(txtMenuItem[i].text,txtMenuItem[i].callback,100));
			if(i==1 || i==3) {
				contextMenu.addSeparator();
			}
		}
		map2.addContextMenu(contextMenu); 
		if($("#deliverLng").val()!=""&&$("#deliverLat").val()!=""&&$("#startLng").val()!=""&&$("#startLat").val()!="")
		{
			var startPoint=new BMap.Point(parseFloat($("#startLng").val()),parseFloat($("#startLat").val()));
			start[0]=parseFloat($("#startLng").val());
			start[1]=parseFloat($("#startLat").val());
			var endPoint=new BMap.Point(parseFloat($("#deliverLng").val()),parseFloat($("#deliverLat").val()));
			end[0]=parseFloat($("#deliverLng").val());
			end[1]=parseFloat($("#deliverLat").val());
			map2.centerAndZoom(startPoint, 10); 
			driving.search(startPoint, endPoint);
		}
		//地图加载完毕
		map2.addEventListener('tilesloaded',function(){
			if(isfirst2){
				isfirst2=false;
				map2.centerAndZoom(point, 13);
    			map2.addOverlay(new BMap.Marker(point));
			}
		});
		
	}else{
		$.scojs_message("位置不准确,请重新编辑地区", $.scojs_message.TYPE_ERROR);
	}
	
}

$(document).ready(function(){
	if(type=="paotui"){
		$("#deliverTime").datetimepicker({ format: 'yyyy-mm-dd HH:ii', language: 'zh-CN', minView: 'hour', startView: 'day', pickDate: false, pickTime: false, inputMask: false, autoclose: true });
		$("#startTime").datetimepicker({ format: 'yyyy-mm-dd HH:ii', language: 'zh-CN', minView: 'hour', startView: 'day', pickDate: false, pickTime: false, inputMask: false, autoclose: true });
		$.get(ctx+"/errand/up/orderTypeList",{'companyId':$("#companyId2").val()},function(data){
			var text="";
			var otherServices = "";
			if(data==null || data.length==0){
				text="当前公司没有跑腿类型";
				$(".startAddress").text("任务起点");
				$(".deliverAddress").text("任务终点");
				orderType=null;
				areaId=null;
				endAdd=null;
			}else{
				for(var i=0;i<data.length;i++){
					if(data[i].id==orderType){
						 text+="<li class='active orderTypeItem' errandValuationMethod='"+data[i].errandValuationMethod+"' startHint='"+data[i].startHint+"' endHint='"+data[i].endHint+"' endAddress='"+data[i].endAddress+"' areaId='"+data[i].areaId+"'><a data-toggle='tab' class='navigation' type='"+data[i].id+"'>"+data[i].typeName+"</a></li>";
							var starthint = data[i].startHint;
							var endhint = data[i].endHint
							$(".startAddress").text(starthint==null||starthint==""?"任务起点":starthint);
							$(".deliverAddress").text(endhint==null||endhint==""?"任务终点":endhint);
							areaId=data[i].areaId;
							endAdd=data[i].endAddress;
							areaWeightId=data[i].areaWeightId;
							initialize2();
							if(data[i].errandValuationMethod!=true){
					    		$("#valuationType_zj").text("定价金额");
					    	}else{
					    		$("#valuationType_zj").text("打表金额");
					    	}
							if(data[i].otherServices != "" && data[i].otherServices.length >0){
								for (var int = 0; int < data[i].otherServices.length; int++) {
									otherServices += "<label><input type='checkbox' name='otherServices' value='" + data[i].otherServices[int].id +"'/>"+ data[i].otherServices[int].otherServices +"</label>&nbsp;&nbsp;&nbsp;&nbsp;";
								}
							}
							$("#otherServices").html(otherServices);
							var otherServices = $("input[name='otherServices']");
							var service = addServices.split(",");
							if(otherServices.length>0){
								for(var j=0;j<otherServices.length;j++){
									for(var h=0;h<service.length;h++){
										if(service[h] == otherServices[j].value){
											otherServices[j].checked=true;
										}
									}
								}
							}
							$.get(ctx+'/member/findByPhone',{'phone':$("#passengerPhone").val(),'couponType':'paotui','couponTypeId':orderType},function(data){

								if(data.passenger!=null){
									$("#companyName").val(data.passenger.companyName);
									$("#passengerId").val(data.passenger.id);
									$("#passengerName").val(data.passenger.name);
									$("#clientVirtual2").text(data.passenger.drawMoney+data.passenger.nodrawMoney+"元");
									if(data.passenger.inBlackList){
										$("#membertype2").html("黑名单");
									}else{
										$("#membertype2").html(data.passenger.typeStr);
									}
									if(data.coupons!=null&&data.coupons.length>0){
										var text="";
										for(var i=0;i<data.coupons.length;i++){
											text+= "<option value='"+data.coupons[i].id+"'>"+data.coupons[i].couponRule.title+"</option>";
										}
										$("#errand_couponId").empty();
										if(text!=""){
											$("#errand_couponInput").css("display","block");
											$("#errand_couponId").append(text);
										}
									}else{
										$("#errand_couponInput").css("display","none");
										$("#errand_couponId").empty();
									}
									$("#companyId2 option").each(function(index,element){
									  	if($(element).attr("value")==data.passenger.companyId){
									 		$(element).attr("selected","selected");
									 		return false;
									 	}
									});
									
								}else{
									$("#errand_couponInput").css("display","none");
									$("#errand_couponId").empty();
									$("#membertype2").html("新客户");
									$("#passengerName").val("先生/女士");
								}
							});
					}else{
						text+="<li  class='orderTypeItem' otherServices='"+JSON.stringify(data[i].otherServices)+"' errandValuationMethod='"+data[i].errandValuationMethod+"' startHint='"+data[i].startHint+"' endHint='"+data[i].endHint+"' endAddress='"+data[i].endAddress+"' areaId='"+data[i].areaId+"'><a data-toggle='tab' class='navigation' type='"+data[i].id+"'>"+data[i].typeName+"</a></li>";
					}
				}
			}
			
			$("#title").html(text);
		},"json")
	}
	
});

$("#passengerPhone").change(function(){
	$.get(ctx+'/member/findByPhone',{'phone':$("#passengerPhone").val(),'couponType':'paotui','couponTypeId':orderType},function(data){

		if(data.passenger!=null){
			$("#companyName").val(data.passenger.companyName);
			$("#passengerId").val(data.passenger.id);
			$("#passengerName").val(data.passenger.name);
			$("#clientVirtual2").text(data.passenger.drawMoney+data.passenger.nodrawMoney+"元");
			if(data.passenger.inBlackList){
				$("#membertype2").html("黑名单");
			}else{
				$("#membertype2").html(data.passenger.typeStr);
			}
			if(data.coupons!=null&&data.coupons.length>0){
				var text="";
				for(var i=0;i<data.coupons.length;i++){
					text+= "<option value='"+data.coupons[i].id+"'>"+data.coupons[i].couponRule.title+"</option>";
				}
				$("#errand_couponId").empty();
				if(text!=""){
					$("#errand_couponInput").css("display","block");
					$("#errand_couponId").append(text);
				}
			}else{
				$("#errand_couponInput").css("display","none");
				$("#errand_couponId").empty();
			}
			$("#companyId2 option").each(function(index,element){
			  	if($(element).attr("value")==data.passenger.companyId){
			 		$(element).attr("selected","selected");
			 		return false;
			 	}
			});
			
		}else{
			$("#errand_couponInput").css("display","none");
			$("#errand_couponId").empty();
			$("#membertype2").html("新客户");
			$("#passengerName").val("先生/女士");
		}
		
		if(timeStr!=null&&distance!=null){
			
			 $.post(ctx+"/errand/up/getPrice",
					   {areaId:areaId,
				 		areaWeightId:areaWeightId,
				 		couponId:$("#errand_couponId").val(),
				 		weight:$("#weight").val(),
				 		thanksCash:$("#thanksCash").val(),
				 		goodsCash:$("#goodsCash").val(),
				 		protectPrice:$("#protectPrice").val(),
					    time:timeStr,
					    mileage:distance},function(data){
					    	$("#shouldPay").val(data.money);
					    	$("#startPrice").val(data.startPrice);
					    	$("#mileagePrice").val(data.mileagePrice);
					    	$("#travelTimePrice").val(data.travelTimePrice);
					    	$("#travelTime").val(data.travelTime);
					    	$("#mileage").val(data.mileage);
					    	$("#weightPrice").val(data.weightPrice);
					    	$(".errand_travelTime").text("预计时间:"+data.travelTime+"分钟");
					       	$(".errand_mileage").text("预计路程:"+data.mileage+"公里");
					    },"json");
		}
	});
});	

$("#companyId2").change(function(){
	
	$.get(ctx+"/errand/orderTypeList",{'companyId':$(this).val()},function(data){
		var text="";
		if(data==null || data.length==0){
			text="当前公司没有跑腿类型";
			$(".startAddress").text("任务起点");
			$(".deliverAddress").text("任务终点");
			orderType=null;
			areaId=null;
			endAdd=null;
		}else{
			for(var i=0;i<data.length;i++){
				if(i==0){
					if(data[i].errandValuationMethod!=true){
			    		$("#valuationType_zj").text("定价金额");
			    	}else{
			    		$("#valuationType_zj").text("打表金额");
			    	}
				}
				if(data[i].id==orderTypeId){
					text+="<li class='active orderTypeItem' errandValuationMethod='"+data[i].errandValuationMethod+"' startHint='"+data[i].startHint+"' endHint='"+data[i].endHint+"' endAddress='"+data[i].endAddress+"' areaId='"+data[i].areaId+"'><a data-toggle='tab' class='navigation' type='"+data[i].id+"'>"+data[i].typeName+"</a></li>";
					var starthint = data[i].startHint;
					var endhint = data[i].endHint
					$(".startAddress").text(starthint==null||starthint==""?"任务起点":starthint);
					$(".deliverAddress").text(endhint==null||endhint==""?"任务终点":endhint);
					orderType=data[i].id;
					areaId=data[i].areaId;
					endAdd=data[i].endAddress;
				}else{
					text+="<li  class='orderTypeItem' errandValuationMethod='"+data[i].errandValuationMethod+"' startHint='"+data[i].startHint+"' endHint='"+data[i].endHint+"' endAddress='"+data[i].endAddress+"' areaId='"+data[i].areaId+"'><a data-toggle='tab' class='navigation' type='"+data[i].id+"'>"+data[i].typeName+"</a></li>";
				}
			}
		}
		
		$("#title").html(text);
	},"json");
	
});
$("li[specify=false]").click(function(){
	$("#startLat").val("");
	$("#startLng").val("");
	$("#startAddress").val("");
	$("#detailedAddress").val("");
	start = new Array();
	
});
$('#deliverTime').change(function(){
	  var begin=new Date($('#deliverTime').val().replace(/-/g,"/"));
      var end=new Date();
      var startTime = new Date($('#startTime').val().replace(/-/g,"/"));
   	   if(begin!=null&&end!=null&&begin-end<=0){
			 $.scojs_message("交付日期要在当前日期之后!", $.scojs_message.TYPE_ERROR);
      	}
   	   var li =$(" .navigation li[class='active']");
   	  if(li.children("a").attr("type")=="qusong"){
    	if(begin!=null&&startTime&&begin-startTime<=0){
			 $.scojs_message("交件时间必须在取件时间之后!", $.scojs_message.TYPE_ERROR);
        }
   	  }   
});
$('#startTime').change(function(){
	var end=new Date($('#deliverTime').val().replace(/-/g,"/"));
    var begin=new Date($('#startTime').val().replace(/-/g,"/"));
   	if(begin!=null&&end!=null&&end-begin<=0){
			 $.scojs_message("取件时间要在交件时间之前!", $.scojs_message.TYPE_ERROR);
    }
   	if(begin!=null&&end!=null&&begin-(new Date())<=0){
    	 $.scojs_message("取件时间要在当前时间之后!", $.scojs_message.TYPE_ERROR);
    }
}); 
$("#errandCreate").click(function(){
	$("#errandCreate").attr("disabled","disabled");
	if($("#content").val().trim()==''){
		$.scojs_message("请填写任务内容", $.scojs_message.TYPE_ERROR);
		$("#errandCreate").removeAttr("disabled");
		return;
	}
	if($("#content").val().length>200){
		$.scojs_message("任务内容应小于200字", $.scojs_message.TYPE_ERROR);
		$("#errandCreate").removeAttr("disabled");
		return;
	}
	var begin=new Date($('#startTime').val().replace(/-/g,"/"));
   	if(begin.getTime()-new Date().getTime()<0){
   		$('#startTime').val(new Date(new Date().getTime()+1000*60*3).Format("yyyy-MM-dd hh:mm"));
    }
	if(endAdd){
		if($("#deliverAddress").val()==''){
			$.scojs_message("请填写地址", $.scojs_message.TYPE_ERROR);
			$("#errandCreate").removeAttr("disabled");
			return;
		}
	}
	
	if($("#passengerPhone").val()==''){
		$.scojs_message("请填写客户电话", $.scojs_message.TYPE_ERROR);
		$("#errandCreate").removeAttr("disabled");
		return;
	}
	if($("#passengerName").val()==''){
		$.scojs_message("请填写客户姓名", $.scojs_message.TYPE_ERROR);
		$("#errandCreate").removeAttr("disabled");
		return;
	}
	if($("#companyId2").val()==''){
		 $.scojs_message("请选择公司", $.scojs_message.TYPE_ERROR);
		 $("#errandCreate").removeAttr("disabled");
		return;
	}
	
	if($("#shouldPay").val()==""){
			$.scojs_message("请填写定价金额", $.scojs_message.TYPE_ERROR);
			$("#errandCreate").removeAttr("disabled");
			return;
	}else if($("#shouldPay").val()!=""){
		var moneyReg=/^(\d+)(.[0-9]{0,1})?$/;
	   if(!moneyReg.test($("#shouldPay").val())){
				$.scojs_message("定价金额格式不正确,例:12.5", $.scojs_message.TYPE_ERROR);
				$("#errandCreate").removeAttr("disabled");
				return;
	     }
		
	}
/**	if($("#goodsCash").val()==""){
		$.scojs_message("请填写商品金额", $.scojs_message.TYPE_ERROR);
		$("#errandCreate").removeAttr("disabled");
		return;
	}
	if($("#weight").val()==""){
		$.scojs_message("请填写商品重量", $.scojs_message.TYPE_ERROR);
		$("#errandCreate").removeAttr("disabled");
		return;
	}
	if($("#thanksCash").val()==""){
		$.scojs_message("请填写感谢费用金额", $.scojs_message.TYPE_ERROR);
		$("#errandCreate").removeAttr("disabled");
		return;
	}
	if($("#protectPrice").val()==""){
		$.scojs_message("请填写保价金额", $.scojs_message.TYPE_ERROR);
		$("#errandCreate").removeAttr("disabled");
		return;
	}*/
	
	/**if($("#startAddress").attr("lat")=="" && $("#deliverAddress").attr("lat")==""){
		$.scojs_message("起点和终点请至少填写一项", $.scojs_message.TYPE_ERROR);
		$("#errandCreate").removeAttr("disabled");
		return;
	}*/
	if($("#shouldPay").val()==""){
		$.scojs_message("请填写预算金额", $.scojs_message.TYPE_ERROR);
		$("#errandCreate").removeAttr("disabled");
		return;
	}
	if($("#shouldPay").val()>10000){
		$.scojs_message("订单价格超出限制，最高10000", $.scojs_message.TYPE_ERROR);
		$("#errandCreate").removeAttr("disabled");
		return;
	}
	
	
	

	var startAddress;
		startAddress= $("#startAddress").val();	
	
	var deliverAddress;
	     deliverAddress = $("#deliverAddress").val();
	if(startAddress=="" && deliverAddress==""){
	 	$.scojs_message("起点和终点请至少填写一项", $.scojs_message.TYPE_ERROR);
	 	$("#errandCreate").removeAttr("disabled");
	 	return;
	}     
	var otherServices = "";
	     $("input[name=otherServices]:checked").each(function(index,element){
				otherServices += $(element).val() + ",";
			});
//		var endPhones =  $("#passengerPhone").val();
	$.ajax({ type: "POST",
             url: ctx+"/errand/up/create",
             data: {
            	 passengerId:$("#passengerId").val(),
            	 passengerName:$("#passengerName").val(),
            	 passengerPhone:$("#passengerPhone").val(),
            	 companyId:$("#companyId2").val(),
            	 startAddress:startAddress,
            	 startDetailed:$("#startDetailedAddress").val(),
            	 startLat:$("#startAddress").attr("lat"),
				 startLng:$("#startAddress").attr("lng"),
				 content:$("#content").val(),
				 startTime:$("#startTime").val(),
            	 deliverAddress:deliverAddress,
            	 endDetailed:$("#deliverDetailedAddress").val(),
            	 deliverLat:$("#deliverAddress").attr("lat"),
            	 deliverLng:$("#deliverAddress").attr("lng"),
            	 orderTypeId:orderType,
            	 imgs:$("#imgsUrl").val(),
            	 startPrice:$("#startPrice").val(),
            	 mileagePrice:$("#mileagePrice").val(),
            	 travelTimePrice:$("#travelTimePrice").val(),
            	 travelTime:$("#travelTime").val(),
            	 mileage:$("#mileage").val(),
//            	 companyName:$("#companyName").val(),
            	 shouldPay:$("#shouldPay").val(),
            	 goodsCash:$("#goodsCash").val(),
            	 thanksCash:$("#thanksCash").val(),
            	 protectPrice:$("#protectPrice").val(),
            	 weight:$("#weight").val(),
            	 weightPrice:$("#weightPrice").val(),
            	 otherServices:otherServices,
            	 couponId:$("#errand_couponId").val(),
            	 
            	
             },	
             dataType: "json",
             success: function(data){ 
            	 if(data.success){
            		 $.scojs_message("下单成功", $.scojs_message.TYPE_OK);
//            		 window.opener.location.reload(true);
            		 setTimeout(function(){
	            		 window.close();
	     				},500);
            	 }else{
            		 $.scojs_message("跑腿下单失败", $.scojs_message.TYPE_ERROR);
            		 $("#errandCreate").removeAttr("disabled");
            		 return;
            	 }
             }
      });
	
	  
	  issubmit=true;

	
});

//定位
$(".btn-Address").click(function(){
	var input =  $(this).parent().parent().find("input");
	
	var str = $(this).parent().parent().find("input").val();
	if(str==''){
		$.scojs_message("请填写地址", $.scojs_message.TYPE_ERROR);
	}else{
		map2.clearOverlays();
		var local = new BMap.LocalSearch(map2, {
			renderOptions:{map: map2, autoViewport:true}
		});
		local.search(str);
		
		local.setInfoHtmlSetCallback(function(poi,html){
			 var str = ($(html).text().substr(4).split("电话"))[0];
	    	   var string;
	    	   
	    	   if(str.indexOf("段")==-1){
		    		  if(str.indexOf("路")==-1){
		    			  if(str.indexOf("街")==-1){
		    				  if(str.indexOf("号")==-1){
		    					  string =str;
		    				  }else{
		    					  string=str.substring(0,str.indexOf(/\d+号/.exec(str)[0]));
		    				  }
		    			  }else{
		    				 string = str.substring(0,str.indexOf("街")+1);
		    			  }
		    		  }else{
		    			  string = str.substring(0,str.indexOf("路")+1);
		    		  }
		    	   }else{
		    		   string = str.substring(0,str.indexOf("段")+1);
		    	   }	
	    	   input.val(string+poi.marker.getTitle());
	    	   input.attr("lng",poi.marker.point.lng);
	    	   input.attr("lat",poi.marker.point.lng);
	    	   var i = input.attr("index");
	    	   var point=new BMap.Point(poi.marker.point.lng,poi.marker.point.lat);
	    	   addressPoint[i]= point;
		    	var title = poi.marker.getTitle();
		        var markers = map2.getOverlays();
				for(var i=0;i<markers.length;i++){
					markers[i].show();
				}
		        if(addressPoint.length>1){
		        	driving.search(addressPoint[0], addressPoint[1]);
				    poi.marker.hide(); 
		        }
	    });
	}
});
$("#weight").change(function(){
	$.post(ctx+"/errand/up/getPrice",
			   {areaId:areaId,
				areaWeightId:areaWeightId,
				couponId:$("#errand_couponId").val(),
				weight:$("#weight").val(),
				thanksCash:$("#thanksCash").val(),
				goodsCash:$("#goodsCash").val(),
				protectPrice:$("#protectPrice").val(),
			    time:timeStr,
			    mileage:distance},function(data){							    	
			    	$("#shouldPay").val(data.money);
			    	$("#startPrice").val(data.startPrice);
			    	$("#mileagePrice").val(data.mileagePrice);
			    	$("#travelTimePrice").val(data.travelTimePrice);
			    	$("#travelTime").val(data.travelTime);
			    	$("#weightPrice").val(data.weightPrice);
			    	$("#mileage").val(data.mileage);
					$(".mileage_text").text("预计路程:"+data.mileage+"公里");
					$(".travelTime_text").text("预计时间:"+data.travelTime+"分钟");
			    },"json");
});

$("#errand_couponId").change(function(){
	if(null == areaId || null == areaWeightId){
		$.scojs_message("该公司没有开通此类型，不能下单", $.scojs_message.TYPE_ERROR);
		return;
	}
	$.post(ctx+"/errand/up/getPrice",
			   {areaId:areaId,
				areaWeightId:areaWeightId,
				weight:$("#weight").val(),
				thanksCash:$("#thanksCash").val(),
				goodsCash:$("#goodsCash").val(),
				protectPrice:$("#protectPrice").val(),
				couponId:$("#errand_couponId").val(),
			    time:timeStr,
			    mileage:distance},function(data){							    	
			    	$("#shouldPay").val(data.money);
			    	$("#startPrice").val(data.startPrice);
			    	$("#mileagePrice").val(data.mileagePrice);
			    	$("#travelTimePrice").val(data.travelTimePrice);
			    	$("#travelTime").val(data.travelTime);
			    	$("#weightPrice").val(data.weightPrice);
			    	$("#mileage").val(data.mileage);
					$(".mileage_text").text("预计路程:"+data.mileage+"公里");
					$(".travelTime_text").text("预计时间:"+data.travelTime+"分钟");
			    },"json");
});

$("#thanksCash").change(function(){
	$.post(ctx+"/errand/up/getPrice",
			   {areaId:areaId,
				areaWeightId:areaWeightId,
				weight:$("#weight").val(),
				couponId:$("#errand_couponId").val(),
				thanksCash:$("#thanksCash").val(),
				goodsCash:$("#goodsCash").val(),
				protectPrice:$("#protectPrice").val(),
			    time:timeStr,
			    mileage:distance},function(data){							    	
			    	$("#shouldPay").val(data.money);
			    	$("#startPrice").val(data.startPrice);
			    	$("#mileagePrice").val(data.mileagePrice);
			    	$("#travelTimePrice").val(data.travelTimePrice);
			    	$("#travelTime").val(data.travelTime);
			    	$("#weightPrice").val(data.weightPrice);
			    	$("#mileage").val(data.mileage);
					$(".mileage_text").text("预计路程:"+data.mileage+"公里");
					$(".travelTime_text").text("预计时间:"+data.travelTime+"分钟");
			    },"json");
});

$("#goodsCash").change(function(){
	$.post(ctx+"/errand/up/getPrice",
			   {areaId:areaId,
				areaWeightId:areaWeightId,
				weight:$("#weight").val(),
				couponId:$("#errand_couponId").val(),
				thanksCash:$("#thanksCash").val(),
				goodsCash:$("#goodsCash").val(),
				protectPrice:$("#protectPrice").val(),
			    time:timeStr,
			    mileage:distance},function(data){							    	
			    	$("#shouldPay").val(data.money);
			    	$("#startPrice").val(data.startPrice);
			    	$("#mileagePrice").val(data.mileagePrice);
			    	$("#travelTimePrice").val(data.travelTimePrice);
			    	$("#travelTime").val(data.travelTime);
			    	$("#weightPrice").val(data.weightPrice);
			    	$("#mileage").val(data.mileage);
					$(".mileage_text").text("预计路程:"+data.mileage+"公里");
					$(".travelTime_text").text("预计时间:"+data.travelTime+"分钟");
			    },"json");
});

$("#protectPrice").change(function(){
	$.post(ctx+"/errand/up/getPrice",
			   {areaId:areaId,
				areaWeightId:areaWeightId,
				weight:$("#weight").val(),
				thanksCash:$("#thanksCash").val(),
				couponId:$("#errand_couponId").val(),
				goodsCash:$("#goodsCash").val(),
				protectPrice:$("#protectPrice").val(),
			    time:timeStr,
			    mileage:distance},function(data){							    	
			    	$("#shouldPay").val(data.money);
			    	$("#startPrice").val(data.startPrice);
			    	$("#mileagePrice").val(data.mileagePrice);
			    	$("#travelTimePrice").val(data.travelTimePrice);
			    	$("#travelTime").val(data.travelTime);
			    	$("#weightPrice").val(data.weightPrice);
			    	$("#mileage").val(data.mileage);
					$(".mileage_text").text("预计路程:"+data.mileage+"公里");
					$(".travelTime_text").text("预计时间:"+data.travelTime+"分钟");
			    },"json");
});
var inputC;
$(".autoComplete").focus(function(){
	inputC = $(this);
	$(".autoComplete").AutoComplete({
	    data: ctx+"/order/getHistoryInputedPlace",
		ajaxDataType: "json",
	    itemHeight: 24,
	    max:1,
	    width: "auto",
	    async: true,
	    listStyle: "custom",
	    emphasis: false,
	    matchHandler: function(keyword, data){
	        return true;
	    },
	    createItemHandler: function(index, data){
	    	if(data.address.length>14){
        		return "<span title='"+data.address+"'>"+data.address.substring(0,14)+"</span>";
        	}
            return "<span title='"+data.address+"'>"+data.address+"</span>";
	    },
	    afterSelectedHandler: function(data){
	    	var address = (data.address).split(" ");
	    	
	    	inputC.val(data.address);
	    	var i = inputC.attr("index");
	        var p = new BMap.Point(data.longitude,data.latitude);
	        inputC.attr("lng",data.longitude);
	        inputC.attr("lat",data.latitude);
	        addressPoint[i]=p;
		    var marker = new BMap.Marker(p); 
		    if(addressPoint.length==1){
				 $.post(ctx+"/errand/up/getPrice",
					   {areaId:areaId,
					 	areaWeightId:areaWeightId,
	        			weight:$("#weight").val(),
	        			couponId:$("#errand_couponId").val(),
	        			thanksCash:$("#thanksCash").val(),
						goodsCash:$("#goodsCash").val(),
						protectPrice:$("#protectPrice").val(),
					    time:"",
					    mileage:""},function(data){	
					    	$("#shouldPay").val(data.money==null?0:data.money);
					    	$("#startPrice").val(data.startPrice);
					    	$("#mileagePrice").val(data.mileagePrice);
					    	$("#travelTimePrice").val(data.travelTimePrice);
					    	$("#travelTime").val(data.travelTime);
					    	$("#mileage").val(data.mileage);
					    	$("#weightPrice").val(data.weightPrice);
					    	$(".errand_travelTime").text("预计时间:"+data.travelTime+"分钟");
					       	$(".errand_mileage").text("预计路程:"+data.mileage+"公里");
					    },"json");
		    }
		    if(addressPoint.length>1){
				driving.search(addressPoint[0], addressPoint[1]);
				
	        }else{
	        	 map2.addOverlay(marker);
			     markerComplete(data.longitude,data.latitude);
	        }
		   
	    }
	}).AutoComplete('show');
});
$("#btn-deliverAddress").click(function(){
	if($("#deliverAddress").val()==''){
		$.scojs_message("请填写交付地点", $.scojs_message.TYPE_ERROR);
	}else{
		map2.clearOverlays();
		var local = new BMap.LocalSearch(map2, {
    	  renderOptions:{map: map2, autoViewport:true}
    	});
	    local.search($("#deliverAddress").val());
	    local.setInfoHtmlSetCallback(function(poi,html){
	    	 var str = ($(html).text().substr(4).split("电话"))[0];
	    	   var string;
	    	   if(str.indexOf("段")==-1){
		    		  if(str.indexOf("路")==-1){
		    			  if(str.indexOf("街")==-1){
		    				  if(str.indexOf("号")==-1){
		    					  string =str;
		    				  }else{
		    					  string=str.substring(0,str.indexOf((/\d+号/.exec(str))[0]));
		    				  }
		    			  }else{
		    				 string = str.substring(0,str.indexOf("街")+1);
		    			  }
		    		  }else{
		    			  string = str.substring(0,str.indexOf("路")+1);
		    		  }
		    	   }else{
		    		   string = str.substring(0,str.indexOf("段")+1);
		    	   }	
	    	  
	    	   $("#deliverAddress").val(string+poi.marker.getTitle());
	    	   $("#deliverDetailedAddress").val("");
	    	   $("#deliverLng").val(poi.marker.point.lng);
		       $("#deliverLat").val(poi.marker.point.lat);
		        end[0]=poi.marker.point.lng;
		        end[1]=poi.marker.point.lat;
		    	var title = poi.marker.getTitle();
		        var markers = map2.getOverlays();
				for(var i=0;i<markers.length;i++){
					markers[i].show();
				}
		        if(start.length!=0){
		        	var startPoint=new BMap.Point(start[0], start[1]);
					var endPoint=new BMap.Point(end[0],end[1]);
					driving.search(startPoint, endPoint);
				    poi.marker.hide(); 
		        }
	    });
	}
});

$("#eFixPrice").click(function(e){
	if(this.checked){
		$("#efixPrice_div").slideDown();
	}else{
		$("#efixPrice_div").slideUp();
	}
});

$("#shareImage_btn").click(function(){
	var imgCount = $("#imgs").children("img").length;		
	if(imgCount<=4){
		$("#shareImage_file").click();			
	}

});
$("#deleteImg").click(function(){
	
	
	var imgCount = $("#imgs").children("img").length;
		if(imgCount>0){
		var imgs = $("#imgs").children("img");
		 $(imgs.get(imgs.length-1)).remove();
		 $.scojs_message("删除成功", $.scojs_message.TYPE_OK);					
		 $("#shareImage_btn").css("display","block");
		var paths =  $("#imgsUrl").val().split(",");
		var newpath = new Array();
		for(var i=0;i<paths.length-1;i++){				
			newpath[i]=paths[i];
		}
		   $("#imgsUrl").val(newpath.toString());
		   
		}			
		
	
});
var flag = false;
//切换类型
 $(document).on("click",".orderTypeItem",function(){
       var li = $(this);
	   var endAddress =  li.attr("endAddress");
	   var endhint = li.attr("endhint");
	   areaId=li.attr("areaid");
	   var type = li.children("a").attr("type")
	   var starthint = li.attr("starthint");
		$(".startAddress").text(starthint==null||starthint==""||starthint=="null"? "任务起点":starthint);
		$(".deliverAddress").text(endhint==null||endhint==""||endhint=='null'? "任务终点":endhint);
		orderType=type;
		 $.post(ctx+"/errand/up/getPrice",
				   {areaId:areaId,
			 		areaWeightId:areaWeightId,
			 		weight:$("#weight").val(),
			 		thanksCash:$("#thanksCash").val(),
			 		goodsCash:$("#goodsCash").val(),
			 		couponId:$("#errand_couponId").val(),
			 		protectPrice:$("#protectPrice").val(),
				    time:timeStr,
				    mileage:distance},function(data){							    	
				    	$("#shouldPay").val(data.money);
				    	$("#startPrice").val(data.startPrice);
				    	$("#mileagePrice").val(data.mileagePrice);
				    	$("#travelTimePrice").val(data.travelTimePrice);
				    	$("#travelTime").val(data.travelTime);
				    	$("#weightPrice").val(data.weightPrice);
				    	$("#mileage").val(data.mileage);
				    	if(li.attr("errandValuationMethod")!="true"){
				    		$("#valuationType_zj").text("定价金额");
				    	}else{
				    		$("#valuationType_zj").text("打表金额");
				    	}
				    	$(".errand_travelTime").text("预计时间:"+data.travelTime+"分钟");
				       	$(".errand_mileage").text("预计路程:"+data.mileage+"公里");
				       	
				    },"json");
		 $.get(ctx+'/member/findByPhone',{'phone':$("#passengerPhone").val(),'couponType':'paotui','couponTypeId':orderType},function(data){
				if(data.coupons!=null&&data.coupons.length>0){
					var text="<option value='' >"+"请选择优惠券"+"</option>";
					for(var i=0;i<data.coupons.length;i++){
						text+= "<option value='"+data.coupons[i].id+"'>"+data.coupons[i].couponRule.title+"</option>";
					}
					$("#errand_couponId").empty();
					if(text!=""){
						$("#errand_couponInput").css("display","block");
						$("#errand_couponId").append(text);
					}
				}else{
					$("#errand_couponInput").css("display","none");
					$("#errand_couponId").empty();
				}
			});
    });

$(document).on('change','#shareImage_file',function(){
	if($.trim($(this).val())){
	 	$.ajaxFileUpload({
            url:ctx+'/common/uploaderrandimg',
            secureuri:false,
            fileElementId:'shareImage_file',
            dataType: 'json',
            success: function (data) {

            	if(data.success){
            		$.scojs_message("上传成功", $.scojs_message.TYPE_OK);
                	
            		$("#imgs").append("<img class='img' style='margin:3px 0 0 3px;' src="+ctx+"/"+data.minurl+"></img>");
            	   
            		if($("#imgsUrl").val()==""){
            			
            			$("#imgsUrl").val(data.url+"-"+data.minurl)
           		
            		}else{
            			var path = $("#imgsUrl").val();
            			
            			$("#imgsUrl").val(path+","+data.url+"-"+data.minurl);
            			
            		}     		
            		var imgCount = $("#imgs").children("img").length;
            		if(imgCount==5){
            			$("#shareImage_btn").css("display","none");			
            		}
            		
            	}else{
            		$.scojs_message(result.msg, $.scojs_message.TYPE_ERROR);
            	}
            }
        });
	}
});

//时间格式化
Date.prototype.Format = function(fmt) 
{ 
  var o = { 
    "M+" : this.getMonth()+1,                 //月份 
    "d+" : this.getDate(),                    //日 
    "h+" : this.getHours(),                   //小时 
    "m+" : this.getMinutes(),                 //分 
    "s+" : this.getSeconds(),                 //秒 
    "q+" : Math.floor((this.getMonth()+3)/3), //季度 
    "S"  : this.getMilliseconds()             //毫秒 
  }; 
  if(/(y+)/.test(fmt)) 
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
  for(var k in o) 
    if(new RegExp("("+ k +")").test(fmt)) 
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt; 
}
